package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    /**
     * 修改购物车 商品数量减一
     * @param shoppingCart 商品id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void subtractById(ShoppingCart shoppingCart) {

        // 根据该商品id 查询购物车
        ShoppingCart shoppingCartOne = this.lambdaQuery()
                .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .one();
        if (shoppingCartOne.getNumber() == 1){
            //商品数据为 一 , 从购物车中删除该商品
            this.removeById(shoppingCartOne);
        }else {
            //当商品数据 大于一时 ,将商品数量减一
            shoppingCartOne.setNumber( shoppingCartOne.getNumber() - 1);
            this.updateById(shoppingCartOne);
        }
    }
}
